package com.ly.service.impl;

import cn.hutool.crypto.digest.DigestUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ly.common.StatusEnum;
import com.ly.dao.UserDao;
import com.ly.dao.UserTokenDao;
import com.ly.entity.User;
import com.ly.entity.UserToken;
import com.ly.exp.ServiceException;
import com.ly.rep.LoginRep;
import com.ly.rep.PageRequest;
import com.ly.req.LoginReq;
import com.ly.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

@Service
public class UserServiceImpl implements UserService {
    @Resource
    public UserDao userDao;
    @Resource
    public UserTokenDao userTokenDao;

    @Override
    public Boolean register(User user) {
        if(!user.getPassword().equals(user.getConfirmPassword())){
            throw  new ServiceException(StatusEnum.ERROR.getCode(), "两次密码输入不一致");
        }
        User userQuery = new User();
        userQuery.setUserName(user.getUserName());
        List<User> users = userDao.selectAll(userQuery);
        if(!CollectionUtils.isEmpty(users)){
            throw new ServiceException(StatusEnum.ERROR.getCode(), "用户名称已存在");
        }
        User userQueryEmail = new User();
        userQueryEmail.setEmail(user.getEmail());
        List<User> userEmailList = userDao.selectAll(userQueryEmail);
        Optional<User> _find = userEmailList.stream().filter(u -> u.getEmail().equals(user.getEmail())).findAny();
        if(_find.isPresent()){
            throw new ServiceException(StatusEnum.ERROR.getCode(), "邮箱已注册");
        }

        user.setPassword(DigestUtil.md5Hex(user.getPassword()));
        userDao.insert(user);
        return true;
    }

    @Override
    @Transactional
    public LoginRep login(LoginReq loginReq) {
        User userQuery = new User();
        userQuery.setUserName(loginReq.getUserName());
        userQuery.setPassword(DigestUtil.md5Hex(loginReq.getPassword()));
        User user = userDao.selectByUserAndPassword(userQuery);
        if(Objects.isNull(user)){
            throw  new ServiceException(StatusEnum.UNAUTHORIZED.getCode(), "用户不存在或者用户密码错误");
        }
        LoginRep loginRep = new LoginRep();
        loginRep.setUserId(user.getId());
        loginRep.setImageUrl(user.getImageUrl());
        loginRep.setNickName(user.getNickName());
        long time = new Date().getTime();
        String token = DigestUtil.md5Hex(user.getId()+"_"+time);
        loginRep.setToken(token);
        //在新增token之前，如果存在，需要先删掉
        UserToken userTokenQuery =  userTokenDao.selectByUserId(user.getId());
        if(Objects.nonNull(userTokenQuery)){
            userTokenDao.deleteById(userTokenQuery.getId());
        }
        //把数据新增到 user_token表
        UserToken userToken = new UserToken();
        userToken.setUserId(user.getId());
        userToken.setToken(token);
        userToken.setCreateTime(new Date());
        userToken.setOverdue(30); //默认30分钟过期
        userTokenDao.insert(userToken);
        return loginRep;
    }

    @Override
    public PageInfo<User> page(PageRequest<User> pageRequest) {
        PageHelper.startPage(pageRequest.getPageNum(), pageRequest.getPageSize());
        List<User> users = userDao.selectAll(pageRequest.getQ());
        PageInfo<User> pageInfo = new PageInfo<>(users);
        return pageInfo;
    }
}
